package com.example.app.ui.Contact;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.app.R;
import com.example.app.Entity.User;
import java.util.List;
public class ContactAdapter extends BaseAdapter {
    private Context context;
    private List<User> userList;

    public ContactAdapter(Context context, List<User> userList) {
        this.context = context;
        this.userList = userList;
    }
    @Override
    public int getCount() {
        return userList.size();
    }
    @Override
    public Object getItem(int position) {
        return userList.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        ViewHolder holder;
        if (view == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            view = inflater.inflate(R.layout.contact, null);
            holder = new ViewHolder();
            holder.nameTextView = view.findViewById(R.id.contacttv);
            holder.avatarImageView = view.findViewById(R.id.avatar_iv);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        User user = userList.get(position);
        holder.nameTextView.setText(user.getNickname());

        // 根据avatarUrl加载本地头像资源
        String avatarName = user.getAvatarUrl();
        int resId = context.getResources().getIdentifier(
                avatarName,
                "drawable",
                context.getPackageName()
        );
        if (resId == 0) {
            resId = R.drawable.tx1; // 默认头像
        }
        holder.avatarImageView.setImageResource(resId);

        return view;
    }

    static class ViewHolder {
        TextView nameTextView;
        ImageView avatarImageView;
    }
    public void updateData(List<User> newList) {
        this.userList = newList;
        notifyDataSetChanged();
    }
}